import {
  EditOutlined,
  LeftOutlined,
  SaveOutlined,
  CheckOutlined
} from '@ant-design/icons'
import { Button, Flex, Input, message, Space, Typography } from 'antd'
import React, { FC, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import EditToolbar from './EditToolbar'
import useGetComponentInfo from '../../hooks/useGetComponentInfo'
import { addQuestionFun, updateQuestionInfoFun } from '../../api/list'
import useGetPageInfo from '../../hooks/useGetPageInfo'
import { changeTitle } from '../../store/pageInfoReducer'
import { useDispatch } from 'react-redux'
import { useKeyPress, useRequest } from 'ahooks'
import style from './EditHeader.module.scss'

export default function EditHeader() {
  const nav = useNavigate()
  const disptach = useDispatch()
  const { id } = useParams()
  const { componentsList } = useGetComponentInfo()
  const { title } = useGetPageInfo()
  const [editTitle, setEditTitle] = useState(false)
  const pageInfo = useGetPageInfo()
  const [showSucessResult, setShowSucessResult] = useState(false)

  // 新增问卷
  const { run: addQuestion } = useRequest(
    async () =>
      await addQuestionFun({
        ...pageInfo,
        componentsList
      }),
    {
      manual: true,
      onSuccess: res => {
        message.success(res.message)
        nav(-1)
      }
    }
  )

  // 更新问卷组件列表
  const { run: saveFun, loading } = useRequest(
    async (isPublish: boolean) => {
      return await updateQuestionInfoFun({
        _id: id,
        ...pageInfo,
        publish: isPublish,
        componentsList
      })
    },
    {
      manual: true,
      onSuccess: () => {
        setShowSucessResult(true)
        setTimeout(() => {
          setShowSucessResult(false)
        }, 2000)
      }
    }
  )

  // 根据当前页面判断是新增还是修改
  function unifiedSubmit(isPublish: boolean) {
    // 更新
    if (id) {
      saveFun(isPublish)
    } else {
      addQuestion()
    }
  }

  // Ctrl+S保存
  useKeyPress(['ctrl.s', 'meta.s'], (evnet: KeyboardEvent) => {
    evnet.preventDefault() // 阻止默认事件，防止触发网页的保存
    unifiedSubmit(pageInfo.publish)
  })

  // 监听内容变化实现自动保存
  // useDebounceEffect(
  //   () => {
  //     if (id) {
  //       unifiedSubmit(pageInfo.publish)
  //     }
  //   },
  //   [componentsList, pageInfo],
  //   { wait: 1000 }
  // )

  // 修改标题
  function onChangeInput(event: React.ChangeEvent<HTMLInputElement>) {
    disptach(changeTitle(event.target.value)) // 在失去焦点时处理 trim
  }

  // 保存按钮
  const SaveButton: FC = () => {
    // 保存问卷
    function saveQuestionList() {
      unifiedSubmit(pageInfo.publish)
    }

    return (
      <Button
        type="primary"
        icon={<SaveOutlined />}
        loading={loading}
        onClick={saveQuestionList}
      >
        保存
      </Button>
    )
  }

  // 保存并发布按钮
  const PublishButtion: FC = () => {
    function saveAndPublish() {
      saveFun(true)
      // 跳转到统计页面
      nav(`/question/stat/${id}`)
    }

    return (
      <Button
        type="primary"
        icon={<SaveOutlined />}
        loading={loading}
        onClick={saveAndPublish}
      >
        保存并发布
      </Button>
    )
  }

  const TitleElem: React.FC = () => {
    return (
      <Space>
        {editTitle && (
          <Input
            value={title}
            onBlur={() => setEditTitle(false)}
            onPressEnter={() => setEditTitle(false)}
            onChange={event => onChangeInput(event)}
            style={{ width: '300px' }}
          />
        )}
        {!editTitle && <Typography.Text strong>{title}</Typography.Text>}
        <EditOutlined onClick={() => setEditTitle(!editTitle)} />
      </Space>
    )
  }

  return (
    <Flex
      align="center"
      justify="space-between"
      style={{ height: '100%', position: 'relative' }}
    >
      <Space>
        <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
          返回
        </Button>
        <TitleElem />
      </Space>
      {/* 中间操作栏 */}
      <div
        style={{
          position: 'absolute',
          left: '50%',
          transform: 'translateX(-50%)'
        }}
      >
        <EditToolbar />
      </div>
      <Space>
        {showSucessResult && (
          <Flex align="center" gap={5} style={{ marginRight: 30 }}>
            <div className={style.successIcon}>
              <CheckOutlined />
            </div>
            <div style={{ fontSize: 13 }}>保存成功</div>
          </Flex>
        )}

        <Button>取消</Button>
        <SaveButton />
        <PublishButtion />
      </Space>
    </Flex>
  )
}
